//
//  TapeTableViewController.m
//  MansApp
//
//  Created by lanou3g on 15/7/29.
//  Copyright (c) 2015年 ACH. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "TapeTableViewController.h"
#import "TapePlayerView.h"
@interface TapeTableViewController ()<AVAudioPlayerDelegate>
@property(nonatomic,strong)NSMutableArray *tapeArrays;
@property(nonatomic,strong)TapePlayerView *playerView;
@property(nonatomic,strong)AVAudioPlayer *myPlayer;
@property(nonatomic,strong)NSTimer *playTimer;

@end

@implementation TapeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.navigationItem.title = @"我的录音";
    
    self.navigationController.navigationBar.translucent = NO;
    [self haveTape];
    
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"weibo_backBlack@2x"] style:UIBarButtonItemStylePlain target:self action:@selector(barButtonItemAciton:)];
    
    self.navigationItem.leftBarButtonItem = barButton;

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    
    imageView.image = [UIImage imageNamed:@"background123"];
    
    self.tableView.backgroundView = imageView;
    
    AVAudioSession *avSession = [AVAudioSession sharedInstance];
    [avSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    
    
    [avSession setActive:YES  error:nil];
    
    
}
- (void)barButtonItemAciton:(UIBarButtonItem *)button{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
}

- (TapePlayerView *)playerView{
    
    if (!_playerView) {
        _playerView = [[TapePlayerView alloc]initWithFrame:CGRectMake(0, kP6Height(200), kWidth, kP6Height(150))];
        [_playerView addTarget:self action:@selector(playerButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _playerView;
}

-(void)playerButtonAction:(UIButton *)button{
    switch (button.tag) {
        case 100:
        {
            [self addTimer];
            self.playTimer.fireDate = [NSDate date];
            
            [self.myPlayer play];
        }
            break;
         case 101:
        {
            self.playTimer.fireDate = [NSDate distantFuture];
            [self.myPlayer pause];
        }
            break;
        default:
        {   [self.playTimer invalidate];
            self.playTimer =nil;
            [self.myPlayer stop];
            [self.playerView removeFromSuperview];
        }
            break;
    }
    
    
}

- (NSMutableArray *)tapeArrays{
    
    if (!_tapeArrays) {
        _tapeArrays = [NSMutableArray array];
        
    }
    return _tapeArrays;
}

- (void)haveTape{
    
     NSMutableArray *array = [[ACHdb sharedInstance] showTheAllTape];
    
    for (int i = 0; i < [self.myArray.firstObject count]; i++) {
        NSString *str = array[i];
        if (str && str.length > 0) {
          
            NSMutableArray *arrayA =[NSMutableArray arrayWithArray:[str  componentsSeparatedByString:@"/"]];
            
            [arrayA removeObject:@""];
            [self.tapeArrays addObject:arrayA];
        }
        else{
            [self.tapeArrays addObject:[NSMutableArray array]];
        }
        
        
    }
    
    
    
}




- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   
    return self.tapeArrays.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    return  [self.tapeArrays[section] count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if ([self.tapeArrays[section] count] == 0) {
        return nil;
    }
    return  [self giveMeATitle:section];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.font =[UIFont fontWithName:@"DBLCDTempBlack" size:20];
    cell.textLabel.text = [self.tapeArrays[indexPath.section] objectAtIndex:indexPath.row];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.playerView removeFromSuperview];
    [self.view addSubview: self.playerView];
    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *allPath = [NSString stringWithFormat:@"%@/%@",path,[self.tapeArrays[indexPath.section] objectAtIndex:indexPath.row]];
    self.myPlayer = nil;
    self.myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath: allPath] error:nil];
    [self.myPlayer prepareToPlay];
    self.myPlayer.delegate = self;
    self.playerView.endLabel.text = [NSString stringWithFormat:@"%.1f",self.myPlayer.duration];
    [self addTimer];
    [self.myPlayer play];

    
    
}




- (void)timeAction{
    

    CGFloat  percent = self.myPlayer.currentTime / self.myPlayer.duration + 0.05;
    
    if (percent > 1.0) {
        percent = 1.0;
        
        self.playerView.beginLabel.text = [NSString stringWithFormat:@"%.1f",self.myPlayer.duration];
      
    }else{
        self.playerView.beginLabel.text = [NSString stringWithFormat:@"%.1f",self.myPlayer.currentTime];
    }
    
    self.playerView.progress.progress = percent;
    
}

- (void)addTimer{
    
    if (!self.playTimer) {
        
        self.playTimer  =[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    }
    
}


-  (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    
    flag = YES;
    [self.playTimer invalidate];
    self.playTimer = nil;
  
}

- (NSString *)changeDateWithIndexPath:(NSInteger)path{
    
    NSMutableString *str = [NSMutableString stringWithFormat:@"%@",self.myArray.firstObject[path]];
    
    if (str && str.length != 0) {
        
        
        [str insertString:@"/" atIndex:4];
        [str insertString:@"/" atIndex:7];
        [str insertString:@"/" atIndex:10];
        [str insertString:@":" atIndex:13];
        [str insertString:@":" atIndex:16];
        
        return str;
    }
    else return  @"";
}

-(NSString *)giveMeATitle:(NSInteger)path{
    
    if ([self.myArray.lastObject[path] length] != 0) {
        return self.myArray.lastObject[path];
        
    }
    else{
        return [self changeDateWithIndexPath:path];
    }
    
    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    if (self.playTimer) {
        [self.playTimer invalidate];
        self.playTimer = nil;
    }
    
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
